import traceback
from flask import Blueprint,request
from sqlalchemy import func, and_
import  models
import json
from werkzeug.serving import WSGIRequestHandler
WSGIRequestHandler.protocol_version = "HTTP/1.1"
from config import  log, debug, makeNewSession
import config
from API.yqpost import Yqpost
from botclass.timer import Timer
import datetime


functions = Blueprint('functions',__name__)

# 疫情上报查询
@functions.route("/checkReportBanji", methods=["GET"])
def checkReportBanji():
    session = makeNewSession()
    y = Yqpost()
    d = y.check_report_banji(18107342, session)
    print(d)
    session.close()
    return d

# 疫情上报查询 获取所有班级
@functions.route("/get_classes_all", methods=["POST"])
def get_classes_all():
    session = makeNewSession()
    classes = list(map(lambda cls: cls.classesID, session.query(models.Classes)))
    session.close()
    return {"code":0, "data":classes}

# 疫情上报查询 列表
@functions.route("/yqpost_list", methods=["POST"])
def yqpost_list():
    pass

# 疫情上报查询 提交
@functions.route("/yqpost_post", methods=["POST"])
def yqpost_post():
    getData = request.get_json()
    debug(getData)
    if not getData: return "some args is needed",406
    title = getData["title"]
    banji = getData["banji"]
    time_ = getData["time"]
    session = makeNewSession()
    try:
        task_list = []
        qs = session.query(models.Classes).filter(models.Classes.classesID.in_(banji))
        # groups = list(map(lambda q: q.mainGroup, qs))
        cls_group = {q.classesID:q.mainGroup for q in qs}

        task = dict(
            type="yqpost",
            message_type="groups",
            cls_group=cls_group
        )
        task_list.append(task)

        timer = Timer.genTimer(title, [i for i in range(7)], None, time_, task_list)
        session.add(timer)
        session.commit()
        session.close()
        return "ok"
    except:
        traceback.print_exc()
        session.rollback()
        session.close()
        return "error",500
        


